package threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * # @File  : ScheduledThreadPool.java
 * # @Author: Lomo
 * # @Site  : lomo.space
 * # @Date  : 2021-09-01
 * # @Desc  : newScheduledThreadPool 定长线程池，可执行周期性的任务
 *
 * 适用：执行周期性任务
 */
public class ScheduledThreadPool {

    private static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);

    public static void main(String[] args) {
        testScheduledExecutor();
    }

    //测试定长、可周期执行的线程池
    private static void testScheduledExecutor() {
        for (int i = 0; i < 3; i++) {
            final int index = i;
            //scheduleWithFixedDelay 固定的延迟时间执行任务(这里固定延迟 3s )；scheduleAtFixedRate 固定的频率执行任务
            scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " index:" + index);
                }
            }, 0, 3, TimeUnit.SECONDS);
        }

        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("4秒后...");

        scheduledExecutorService.shutdown();
    }
}
